package com.pixiv.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.json.JSONObject;
import com.pixiv.Entity.RegisterPicture;
import com.pixiv.Entity.User;
import com.pixiv.service.LoginService;
import com.pixiv.service.RegisterService;
import com.pixiv.tools.ProgramStaticGlobal;
import com.pixiv.tools.SendPack;
import com.pixiv.tools.SendPrintWriterPacket;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

@Controller
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private RegisterService registerService;
    @Autowired
    private LoginService loginService;

    /**
     * 获得注册背景图片
     * @param req
     * @param resp
     */
    @RequestMapping("/getBack")
    public void getBack(HttpServletRequest req, HttpServletResponse resp)
    {

        try {
            //初始化图片
            String name = registerService.getPictureInitName();
            File file = new File(ProgramStaticGlobal.getPRealPath(),name);
            FileInputStream fis =  new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();
            IOUtils.copy(fis, outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 前往注册行为
     * @return
     */
    @RequestMapping("gotoRegister")
    public ModelAndView gotoRegister(){
        return new ModelAndView("/pixiv/registerlogin");
    }

    /**
     * 获得验证码
     * @param req
     * @param resp
     */
    @RequestMapping("getCode")
    public void getCode(HttpServletRequest req, HttpServletResponse resp){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(50,25,4,5);
        String s = lineCaptcha.getCode();
        req.getSession().setAttribute("Register_getCode", s);
        try {
            lineCaptcha.write(resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送了注册包
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping("SendRegisterPacket")
    public void SendRegisterPacket(HttpServletRequest req, HttpServletResponse resp){
        String name = req.getParameter("User");
        String code = req.getParameter("Code");
        HttpSession hs = req.getSession();
        User u = loginService.getUserByLoginParameter(name,null);
        if (u == null)
        {
            String Pwd = req.getParameter("PWD");
            if (!hs.getAttribute("Register_getCode").equals(code) )
            {
                SendPrintWriterPacket.sendFlag(resp,1);
            }else
            {
                registerService.registerUserByLoginParameter(name,Pwd);
                SendPrintWriterPacket.sendFlag(resp,2);
            }
        }else
        {
            SendPrintWriterPacket.sendFlag(resp,0);
        }

    }

    /**
     * 获取了注册图片的所有显示
     * @return
     */
    @ResponseBody
    @RequestMapping("getRegisterTable")
    public String getRegisterBackTable(HttpServletRequest req){

        Object picid = req.getParameter("picid");
        System.out.println("picid:" + picid);
        ArrayList<RegisterPicture> list = registerService.getPictures(picid);
        JSONObject json=new JSONObject();
        json.accumulate("size",list.size());
        json.accumulate("count",10);
        json.accumulate("code",0);
        json.accumulate("msg","null");
        json.accumulate("data",list);
        return json.toString();
    }

    @RequestMapping("getPicture")
    public void getPicture(HttpServletRequest req, HttpServletResponse resp)
    {
        try {
            int id = Integer.parseInt(req.getParameter("id"));
            String name = registerService.getPicture(id);
            File file = new File(ProgramStaticGlobal.getPRealPath(),name);
            FileInputStream fis =  new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();
            IOUtils.copy(fis, outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping("deletePicture")
    public String DeletePicture(HttpServletRequest req, HttpServletResponse resp)
    {
        String path = req.getParameter("ID");
        if (path != null)
        {
            int id = Integer.parseInt(path);
            registerService.deletePicture(id);
            return SendPack.getFlag(1);
        }
        return SendPack.getFlag(0);
    }

    @ResponseBody
    @RequestMapping("addPicture")
    public String addPicture(@RequestParam("file") MultipartFile file, HttpServletRequest req)
    {

        System.out.println("addFile");

        String fileName = file.getOriginalFilename();
        String nameType = fileName.substring(fileName.lastIndexOf(".")).toUpperCase();
        String path = ProgramStaticGlobal.getPRealPath() + "/register";
        String uuidName = UUID.randomUUID().toString().replace("-", "") + nameType;
        try {
            file.transferTo(new File(path, uuidName));
            registerService.appendPicture("/register/" + uuidName);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return SendPack.getFlag(1);
    }

}
